import React, { useState, useRef, useEffect } from 'react';
import { lazyLoadImage, preloadImage } from '../../utils/performance';
import './index.css';

interface LazyImageProps {
  src: string;
  alt: string;
  placeholder?: string;
  className?: string;
  style?: React.CSSProperties;
  onLoad?: () => void;
  onError?: () => void;
  preload?: boolean;
  threshold?: number;
}

const LazyImage: React.FC<LazyImageProps> = ({
  src,
  alt,
  placeholder = '',
  className = '',
  style,
  onLoad,
  onError,
  preload = false,
  threshold = 0.1,
}) => {
  const [isLoaded, setIsLoaded] = useState(false);
  const [hasError, setHasError] = useState(false);
  const imgRef = useRef<HTMLImageElement>(null);

  useEffect(() => {
    if (preload) {
      preloadImage(src)
        .then(() => {
          setIsLoaded(true);
          onLoad?.();
        })
        .catch(() => {
          setHasError(true);
          onError?.();
        });
    } else if (imgRef.current) {
      lazyLoadImage(imgRef.current, src);
    }
  }, [src, preload, onLoad, onError]);

  const handleLoad = () => {
    setIsLoaded(true);
    onLoad?.();
  };

  const handleError = () => {
    setHasError(true);
    onError?.();
  };

  return (
    <div className={`lazy-image-container ${className}`} style={style}>
      <img
        ref={imgRef}
        src={isLoaded ? src : placeholder}
        alt={alt}
        className={`lazy-image ${isLoaded ? 'loaded' : ''} ${hasError ? 'error' : ''}`}
        onLoad={handleLoad}
        onError={handleError}
        loading="lazy"
      />
      {!isLoaded && !hasError && (
        <div className="lazy-image-placeholder">
          <div className="loading-spinner" />
        </div>
      )}
      {hasError && (
        <div className="lazy-image-error">
          <span>图片加载失败</span>
        </div>
      )}
    </div>
  );
};

export default LazyImage;
